<template>
	<view class="">
		<view>
			<movable-area class="drag-sort" :style="{ height: boxHeight }" id="drag">
				<movable-view v-for="(item, index) in currentList" :key="index" :x="item.x" :data-index="index"
					@touchstart="touchstart" @touchmove.stop.prevent="touchmove" @touchend="touchend"
					@click="close(index, item)" @longpress="longpressDragItem" :y="item.y" :direction="direction" disabled
					damping="40" :animation="item.animation" class="drag-sort-item" :style="{ height: height+'px' }">

					<view class="text-item">{{item.name}}</view>
					<view class="get-point">取点</view>
					<image src="../../static/icon_feature_remove.png" alt="" class="icon-close" v-if="!item.isFixed && isOperated"></image>

				</movable-view>
			</movable-area>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'drag-sort',
		mixins: [],
		components: {},
		data() {
			return {
				direction: 'vertical',
				windowWidth: 100, //屏幕宽度
				height: 40, // 高度
				currentList: [],
				active: -1, // 当前激活的item
				index: 0, // 当前激活的item的原index
				topY: 0, // 距离顶部的距离
				topX: 0, // 距离左侧偏移位置
				deviationX: 0,
				deviationY: 0, // 偏移量
				moveToNumber: -1,

				scrollHeight: 0,
				boxHeight: '',
				isOperated: true // 是否在可操作的状态
			};
		},
		computed: {
			// boxHeight(){
			//  return (Math.ceil((Number(this.list.length))/5)) * this.height + 'px'
			// }
		},

		props: {
			list: {
				type: Array,
				default: () => {
					return [];
				}
			},
			boxStyle: {
				type: Object,
				default: () => {
					return {};
				}
			},
			// props: {
			//   type: Object,
			//   default: () => {
			//     return {
			//       label: 'name',
			//       // value: 'name'
			//     }
			//   }
			// }
		},
		watch: {
			list: {
				handler() {
					console.log("handler list")
					// debugger
					this.onUpdateCurrentList();
				},
				deep: true
			},
			currentList: {
				handler() {
					this.boxHeight = this.currentList.length * (this.height + 20) + 5 + 'px';
				},
				deep: true
			},
			// isCanEdit(val) {
			// 	console.log("val--"+val)
			// 	this.isOperated = val;
			// }
		},
		created() {
			const res = uni.getSystemInfoSync();
			// this.windowWidth = res.windowWidth;
			this.scrollHeight = res.windowHeight
			this.windowWidth = uni.upx2px(710);
			this.onUpdateCurrentList();
		},
		mounted() {},
		updated() {},
		filters: {},
		methods: {
			changeOperateStatus(isCanOperate) {
				this.isOperated = isCanOperate
			},
			longpressDragItem() {
				this.isOperated = true;
				// this.$emit('longpressItem');
			},
			longpress(state) {
				// this.isOperated = state;
			},
			onUpdateCurrentList(list = this.list) {
				const self = this;

				let arr = [];
				for (const key in list) {
					let height = Math.ceil((Number(key) + 1) / 5) - 1;
					let x = 0;
					if (key <= 4) {
						x = key * this.windowWidth * 0.2;
					} else {
						if ((Number(key) + 1) % 5 === 0) {
							x = 4 * this.windowWidth * 0.2;
						} else {
							x = (((Number(key) + 1) % 5) - 1) * this.windowWidth * 0.2;
						}
					}
					arr.push({
						...list[key],
						isShow: 1,
						index: Number(key),
						SortNumber: Number(key),
						y: key * (this.height + 20),
						x: 0,
						animation: false
					});
				}
				this.currentList = arr;
				console.log("this.currentList--" + JSON.stringify(this.currentList))
			},
			// 根据排序进行重新计算位置
			moveUpdateCurrentList(index) {
				this.moveItem(this.currentList, this.active, index)
				for (const i in this.currentList) {
					let key;
					if (this.currentList[i].SortNumber || this.currentList[i].SortNumber === 0) {
						key = this.currentList[i].SortNumber;
					} else {
						key = Number(i);
					}
					let temobj = {
						...this.currentList[i]
					};
					// debugger
					// this.currentList[i].y = (Math.ceil((Number(key) + 1) / 5) - 1) * this.height;
					this.currentList[i].x = 0
					this.currentList[i].y = i * (this.height + 20);
					this.currentList[i].isShow = 1
					this.currentList[i].index = Number(i)
					this.currentList[i].SortNumber = Number(i)
					// if (index == key) {
					// 	continue;
					// } else {
					// 	// if (key <= 4) {
					// 	// 	this.currentList[i].x = key * this.windowWidth * 0.2;
					// 	// } else {
					// 	// 	if ((Number(key) + 1) % 5 === 0) {
					// 	// 		this.currentList[i].x = 4 * this.windowWidth * 0.2;
					// 	// 	} else {
					// 	// 		this.currentList[i].x = (((Number(key) + 1) % 5) - 1) * this.windowWidth * 0.2;
					// 	// 	}
					// 	// }
					// 	this.currentList[i].x = 0
					// }
				}
				// this.currentList = this.currentList.filter(v => v.isShow);
				this.$emit('change', this.currentList);
			},
			touchstart(e) {
				if (!this.isOperated) {
					return false
				}
				// 计算 x y 轴点击位置
				var query = uni.createSelectorQuery().in(this);
				query.select('#drag').boundingClientRect();
				query.exec(res => {
					this.topY = res[0].top;
					this.topX = res[0].left;
					let touchY = e.touches[0].clientY - res[0].top;
					let touchX = e.touches[0].clientX - res[0].left;
					this.deviationY = touchY % this.height;
					this.deviationX = touchX % (this.windowWidth * 0.2);
					this.active = Number(e.currentTarget.dataset.index);
					this.index = Number(e.currentTarget.dataset.index);
				});
			},
			touchmove(e) {
				if (!this.isOperated) {
					return false
				}
				if (this.active < 0) return;
				let temY = e.touches[0].clientY - this.topY;
				let temX = e.touches[0].clientX - this.topX;
				let touchY = temY - 15;
				// let touchX = temX - this.windowWidth * 0.1;
				this.currentList[this.active].y = touchY;
				// this.currentList[this.active].x = touchX;
				this.currentList[this.active].animation = false;
				this.currentList.every((res, index) => {
					// let absX = Math.abs(touchX - res.x);
					let absY = Math.abs(touchY - res.y);

					// 设置元素定点距离多少进行重排
					if (absY > 15 && absY <= 30 && this.active != index) {
						// debugger
						// let temNumber = this.currentList[index].SortNumber;
						this.moveToNumber = this.currentList[index].SortNumber;
						// this.currentList.every((_res, _index) => {
						// 	if (_res.isShow == 0) {
						// 		return true;
						// 	}
							// console.log("index----------------->" + index + "touchY-->" + touchY + ";res.y-->" + res.y + ";absY -->" + absY)
						// 	console.log("active.sortNum-->" + this.currentList[this.active].SortNumber)
						// 	console.log("index.sortNum-->" + this.currentList[index].SortNumber)
						// 	console.log("_index.sortNum-->" + this.currentList[_index].SortNumber)
						// 	console.log("_res.sortNum-->" + _res.SortNumber)
						// 	// 判断从大像小移还是从小向大移
						// 	if (this.currentList[this.active].SortNumber < this.currentList[index].SortNumber) {
						// 		// 移动元素比目标元素所在位置小，之间元素排序--
						// 		if (
						// 			this.currentList[_index].SortNumber > this.currentList[this.active].SortNumber &&
						// 			this.currentList[_index].SortNumber <= this.currentList[index].SortNumber
						// 		) {
						// 			_res.SortNumber--;
						// 		}
						// 	} else {
						// 		// 反之++
						// 		if (
						// 			this.currentList[_index].SortNumber < this.currentList[this.active].SortNumber &&
						// 			this.currentList[_index].SortNumber >= this.currentList[index].SortNumber
						// 		) {
						// 			_res.SortNumber++;
						// 		}
						// 	}
						// 	return true;
						// }, this);
						// this.currentList[this.active].SortNumber = temNumber;
						this.currentList[this.active].SortNumber = this.moveToNumber;
						return false;
					} else {
						return true;
					}
				}, this);
			},
			touchend(e) {
				if (!this.isOperated) {
					return false
				}
				if (this.active < 0) return;
				if (this.moveToNumber < 0) return;
				this.moveUpdateCurrentList(this.moveToNumber);
				this.currentList.sort(this.compare('SortNumber'));
				if (this.currentList[this.active]) {
					this.currentList[this.active].animation = true;
				}
				this.active = -1;
				this.moveToNumber = -1
				setTimeout(() => {
					this.$emit('dragList', this.currentList);
				}, 500);
			},
			moveItem(arr, fromIndex, toIndex) {
				// 处理负索引
				const startIdx = fromIndex < 0 ? arr.length + fromIndex : fromIndex;
				const endIdx = toIndex < 0 ? arr.length + toIndex : toIndex;

				// 检查索引有效性
				if (startIdx < 0 || startIdx >= arr.length || endIdx < 0 || endIdx >= arr.length) {
					return arr;
				}

				// 取出元素并插入到新位置
				const [item] = arr.splice(startIdx, 1);
				arr.splice(endIdx, 0, item);
				return arr;
			},
			// 关闭按钮
			close(index, item) {
				if (item.isFixed || !this.isOperated) {
					this.$emit('dragItemClick', item, index);
					return;
				};
				let _this = this;
				uni.showModal({
					title: "是否删除当前项？",
					success: (res) => {
						if (res.confirm) {
							this.toDeleteItem(item, index)
						}
					}
				})
			},
			toDeleteItem(item, index) {
				this.currentList.splice(index, 1)
				this.currentList.forEach((item, i) => {
					this.currentList[i].x = 0
					this.currentList[i].y = i * (this.height + 20);
					this.currentList[i].isShow = 1
					this.currentList[i].index = Number(i)
					this.currentList[i].SortNumber = Number(i)
				});
				this.$emit('deleteList', item, this.currentList);
			},
			compare(key) {
				return function(value1, value2) {
					var val1 = value1[key];
					var val2 = value2[key];
					return val1 - val2;
				};
			},
			bubbleSort(array) {
				var i = 0,
					len = array.length,
					j,
					d;
				for (; i < len; i++) {
					for (j = 0; j < len; j++) {
						if (array[i].SortNumber < array[j].SortNumber) {
							d = array[j].SortNumber;
							array[j].SortNumber = array[i].SortNumber;
							array[i].SortNumber = d;
						}
					}
				}
				return array;
			}
		}
	};
</script>

<style lang="less" scoped>
	// @import '~./1px.less';
	.drag-sort {
		width: 100%;
		// min-height: 180rpx;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}
	.drag-sort2 {
		width: 100%;
		// min-height: 180rpx;
		display: flex;
		align-items: center;
		flex-direction: column;
	}

	.drag-sort-item2 {
		display: flex;
		align-items: center;
		justify-content: space-between;
		// height: 160rpx;
		width: 100%;
		color: #fff;
		box-sizing: border-box;
		// background: #fff;
		border-radius: 24rpx;
		border: 2rpx solid rgba(29, 78, 216, 1);
		margin-bottom: 20px;
		padding: 20rpx;

		&.active {
			z-index: 999;
			// border-left: 1px solid #f2f2f2;
			// border-top: 1px solid #f2f2f2;
		}

		.item {
			position: relative;
			flex: 1;
			font-size: 16px;
		}

		.text-item {
			color: rgba(147, 197, 253, 1);
			font-size: 36rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}

		.get-point {
			border-radius: 16rpx;
			padding: 8rpx 30rpx;
			background-color: #3b82f6;
			color: #fff;
			font-size: 28rpx;
		}

		.icon-close {
			position: absolute;
			width: 34rpx;
			height: 34rpx;
			top: 6rpx;
			right: 6rpx;
			z-index: 999;
		}
	}

	.drag-sort-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		// height: 160rpx;
		width: 100%;
		color: #fff;
		box-sizing: border-box;
		border-radius: 24rpx;
		border: 2rpx solid rgba(29, 78, 216, 1);
		margin-bottom: 20px;
		padding: 20rpx;

		&.active {
			z-index: 999;
			// border-left: 1px solid #f2f2f2;
			// border-top: 1px solid #f2f2f2;
		}

		.item {
			position: relative;
			flex: 1;
			font-size: 16px;
		}

		.text-item {
			color: rgba(147, 197, 253, 1);
			font-size: 36rpx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}

		.get-point {
			border-radius: 16rpx;
			padding: 8rpx 30rpx;
			background-color: #3b82f6;
			color: #fff;
			font-size: 28rpx;
		}

		.icon-close {
			position: absolute;
			width: 34rpx;
			height: 34rpx;
			top: 6rpx;
			right: 6rpx;
			z-index: 999;
		}
	}
</style>